package jp.co.ricoh.melody.views.activities;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.Calendar;

import jp.co.ricoh.melody.R;
import jp.co.ricoh.melody.databases.DBManager;
import jp.co.ricoh.melody.models.entities.AlarmData;
import jp.co.ricoh.melody.models.entities.SoundData;
import jp.co.ricoh.melody.presenters.AddAlarmActivityPresenter;
import jp.co.ricoh.melody.presenters.IAddAlarmActivityPresenter;
import jp.co.ricoh.melody.services.AlarmService;
import jp.co.ricoh.melody.utils.CUtil;
import jp.co.ricoh.melody.utils.CommonUtils;
import jp.co.ricoh.melody.utils.Const;
import jp.co.ricoh.melody.utils.ConstantUtils;
import jp.co.ricoh.melody.utils.LogUtils;
import jp.co.ricoh.melody.views.adapters.IDayListView;
import jp.co.ricoh.melody.views.fragments.NoSaveDialogFragment;
import jp.co.ricoh.melody.views.fragments.NoSelectDayDialogFragment;
import jp.co.ricoh.melody.views.fragments.OverrideTimeDialogFragment;
import jp.co.ricoh.melody.views.fragments.ProgressDialogFragment;
import jp.co.ricoh.melody.views.fragments.SoundListDialogFragment;
import jp.co.ricoh.melody.views.fragments.SoundTimeListDialogFragment;

/**
 * Copyright (C) 2016 RICOH Co.,LTD.
 * All rights reserved.
 * Add Alarm Screen and Edit Alarm Screen.
 */
public class AddAlarmActivity extends BaseActivity implements IAddAlarmActivity, View.OnClickListener, View.OnTouchListener, TextView.OnEditorActionListener, View.OnKeyListener {

    private final String TAG = getClass().getName();
    public static final String EXTRA_ALARM_ID = "alarm_id";
    private final float TIME_PICKER_TEXT_SIZE = 20.f;

    private IDayListView mListDay;

    private AlarmData mOldAlarm;

    private Button mCancelBtn, mSaveBtn;
    private TimePicker mTimePicker;
    private CheckBox mRepeatCb;
    private EditText mLabelEdt;
    private ImageView mSoundImg;
    private TextView mSoundTv;
    private TextView mSoundTitleTv;
    private TextView mSoundTimeTv;

    private final IAddAlarmActivityPresenter mAddAlarmActivityPresenter = new AddAlarmActivityPresenter();
    private AlarmData mEditAlarm;
    private SoundData mSoundData;
    private String mSoundTime;
    private int mIdAlarm;
    private AlarmData.AMPM mAmPm = AlarmData.AMPM.AM;
    private boolean mEnabled = true;
    private NoSaveDialogFragment mNoSaveDialog;
    private NoSelectDayDialogFragment mNoSelectDay;
    private OverrideTimeDialogFragment mOverrideTime;
    private LinearLayout mLayoutAddAlarm;
    private LinearLayout mLayoutSound;
    private LinearLayout mLayoutSoundTime;
    SoundListDialogFragment msoundListDialogFragment;

    private BroadcastReceiver acBroadcastReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private IntentFilter intentFilter;
    private MyReceiver receiver;
    public static final String SYS_NOTIFY_AUTH_STATE_CHANGED = "jp.co.ricoh.isdk.sdkservice.auth.SYS_NOTIFY_AUTH_STATE_CHANGED";

    // finish when enter sleeping mode
    public static final String ACTION_POWER_MODE_CHANGED = "jp.co.ricoh.isdk.sdkservice.system.PowerMode.POWER_MODE_RESULT";

    public static final String POWER_MODE = "POWER_MODE";
    public static final String LOGIN_STATUS = "LOGIN_STATUS";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_alarm);
        init();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter = new IntentFilter();
        intentFilter.addAction("EVENT_TYPE_APP_STATE");
        acBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                AddAlarmActivity.this.finish();
            }
        };
        localBroadcastManager.registerReceiver(acBroadcastReceiver, intentFilter);

        receiver = new MyReceiver();
        IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        homeFilter.addAction(SYS_NOTIFY_AUTH_STATE_CHANGED );
        homeFilter.addAction(ACTION_POWER_MODE_CHANGED );
        homeFilter.addAction(Intent.ACTION_SCREEN_OFF);
        homeFilter.addAction(Intent.ACTION_SCREEN_ON);


        registerReceiver(receiver, homeFilter);
    }

    @Override
    public void init() {
        mIdAlarm = getIntent().getIntExtra(EXTRA_ALARM_ID, ConstantUtils.NEW_ALARM_ID);
        setActionBar();
        mLayoutAddAlarm = (LinearLayout) findViewById(R.id.layout_add_alarm);
        setupUI(mLayoutAddAlarm);
        mNoSaveDialog = new NoSaveDialogFragment();
        mNoSelectDay = new NoSelectDayDialogFragment();
        mOverrideTime = new OverrideTimeDialogFragment();
        mLayoutSound = (LinearLayout) findViewById(R.id.layout_sound);
        mLayoutSound.setOnClickListener(this);
        mLayoutSoundTime = (LinearLayout) findViewById(R.id.layout_sound_time);
        mLayoutSoundTime.setOnClickListener(this);
        mListDay = (IDayListView) findViewById(R.id.dayRecyclerView);
        mListDay.onCreate();
        mLabelEdt = (EditText) findViewById(R.id.ed_label);
        mLabelEdt.setOnTouchListener(this);
        mLabelEdt.setOnEditorActionListener(this);
        mLabelEdt.setOnKeyListener(this);

        mRepeatCb = (CheckBox) findViewById(R.id.cb_repeat);
        mTimePicker = (TimePicker) findViewById(R.id.tp);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            applyStyLing(mTimePicker);
        }
        mSoundImg = (ImageView) findViewById(R.id.iv_sound);
        mCancelBtn = (Button) findViewById(R.id.bt_cancel);
        mCancelBtn.setOnClickListener(this);
        mSaveBtn = (Button) findViewById(R.id.bt_save);
        mSaveBtn.setOnClickListener(this);
        mSoundTv = (TextView) findViewById(R.id.tv_sound);
        mRepeatCb = (CheckBox) findViewById(R.id.cb_repeat);
        mSoundTitleTv = (TextView) findViewById(R.id.tv_title_sound);
        mSoundTimeTv = (TextView) findViewById(R.id.tv_sound_time);

        if (mIdAlarm != ConstantUtils.NEW_ALARM_ID) {//edit
            mEditAlarm = mAddAlarmActivityPresenter.getAlarmById(mIdAlarm);
            mLabelEdt.setText(mEditAlarm.getLabel());
            mRepeatCb.setChecked(mEditAlarm.isRepeatEnabled());
            mTimePicker.setCurrentHour(mEditAlarm.getHours());
            mTimePicker.setCurrentMinute(mEditAlarm.getMinutes());
            mListDay.updateAllDay(mEditAlarm.getDays());
            mAmPm = mEditAlarm.getAMPM();
            mSoundData = new SoundData(mEditAlarm.getSoundData().getId(), mEditAlarm.getSoundData().getTitle(), mEditAlarm.getSoundData().getSoundUri(), mEditAlarm.getSoundData().isEnable(), mEditAlarm.getSoundData().isSystemSound());
            mEnabled = mEditAlarm.isEnabled();
            mSoundTime = mEditAlarm.getSoundTime();
        } else {//add
            int dayCurrent = Calendar.getInstance().getTime().getDay();
            mListDay.getDays().get(dayCurrent).setRepeat(true);
            mListDay.getDays().get(dayCurrent).setDrawableEnableAtPosition(true, dayCurrent);
            mSoundData = new SoundData(ConstantUtils.EMPTY_STRING, ConstantUtils.EMPTY_STRING, ConstantUtils.EMPTY_STRING, true, true);
            mSoundTime = "10 sec";
            mAmPm = getAmPm(mTimePicker);
            initDefaultSound();
        }
        mSoundTitleTv.setText(mSoundData.getTitle());
        mSoundTimeTv.setText(mSoundTime);
        boolean[] daysTemp = mListDay.getDaysRepeat();
        mOldAlarm = new AlarmData(mLabelEdt.getText().toString(), mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute(), mAmPm, daysTemp, mRepeatCb.isChecked(), mEnabled, mSoundData, mSoundTime);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cb_repeat: {
                mRepeatCb.setChecked(!mRepeatCb.isChecked());
                break;
            }
            case R.id.bt_cancel: {
                closeAddAlarmActivity(mOldAlarm);
                break;
            }
            case R.id.bt_save: {
                clickButtonSave();
                break;
            }

            case R.id.layout_sound: {
                clickImageViewSound();
                break;
            }

            case R.id.layout_sound_time: {
                clickSoundTime();
                break;
            }
            default:
                break;
        }
    }

    /**
     * set a default sound when add melody
     */
    public void initDefaultSound() {
        RingtoneManager ringtoneMgr = new RingtoneManager(this);
        ringtoneMgr.setType(RingtoneManager.TYPE_ALARM);
        Cursor alarmsCursor = ringtoneMgr.getCursor();
        int alarmsCount = alarmsCursor.getCount();
        if (alarmsCount == 0 && !alarmsCursor.moveToFirst()) {
            return;
        } else {
            while (!alarmsCursor.isAfterLast() && alarmsCursor.moveToNext()) {
                boolean isEnable = true;
                String id = alarmsCursor.getString(RingtoneManager.ID_COLUMN_INDEX);
                String title = alarmsCursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
                String soundUri = ringtoneMgr.getRingtoneUri(alarmsCursor.getPosition()).toString();
                SoundData tempSoundData = new SoundData(id, title, soundUri, isEnable, true);
                mSoundData = tempSoundData;
                break;
            }
        }
    }

    /**
     * send a broadcast with id  at cal.getTimeInMillis()
     *
     * @param alarm
     */
    public void sendBroadcastAddAlarm(AlarmData alarm) {
        Intent mItent = new Intent(getApplicationContext(), AlarmService.class);
        mItent.putExtra(EXTRA_ALARM_ID, alarm.getId());
        Calendar cal = Calendar.getInstance();
        int hour = mTimePicker.getCurrentHour();
        int minute = mTimePicker.getCurrentMinute();
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE, minute);
        cal.set(Calendar.SECOND, 0);
        PendingIntent pending_intent = PendingIntent.getService(getApplicationContext(), alarm.getId(), mItent, 0);
        AlarmManager alarmManager;
        alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending_intent);
    }

    /**
     * @param timePickerDialog
     */
    private void applyStyLing(TimePicker timePickerDialog) {
        Resources system = Resources.getSystem();
        int hourNumberPickerId = system.getIdentifier("hour", "id", "android");
        int minuteNumberPickerId = system.getIdentifier("minute", "id", "android");
        int ampmNumberPickerId = system.getIdentifier("amPm", "id", "android");
        NumberPicker hourNumberPicker = (NumberPicker) timePickerDialog.findViewById(hourNumberPickerId);
        NumberPicker minuteNumberPicker = (NumberPicker) timePickerDialog.findViewById(minuteNumberPickerId);
        NumberPicker ampmNumberPicker = (NumberPicker) timePickerDialog.findViewById(ampmNumberPickerId);
        setNumberPickerStyle(hourNumberPicker);
        setNumberPickerStyle(minuteNumberPicker);
        setNumberPickerStyle(ampmNumberPicker);
    }

    /**
     * set color for text and edge of numberpicker
     *
     * @param numberPicker
     */
    private void setNumberPickerStyle(NumberPicker numberPicker) {
        final int count = numberPicker.getChildCount();
        for (int i = 0; i < count; i++) {
            try {
                // Change divider color.
                Field dividerField = numberPicker.getClass().getDeclaredField("mSelectionDivider");
                dividerField.setAccessible(true);
                ColorDrawable colorDrawable = new ColorDrawable(getResources().getColor(R.color
                        .color_timepicker));
                dividerField.set(numberPicker, colorDrawable);

                // Change text color, text size.
                Field wheelpaint_field = numberPicker.getClass().getDeclaredField("mSelectorWheelPaint");
                wheelpaint_field.setAccessible(true);
                ((Paint) wheelpaint_field.get(numberPicker)).setTextSize(TIME_PICKER_TEXT_SIZE);
                EditText pickerEditText = ((EditText) numberPicker.getChildAt(i));
                pickerEditText.setTextColor(getResources().getColor(R.color.color_text_timepicker));
                pickerEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.dimen_time_picker_text_size));

                numberPicker.invalidate();
            } catch (NoSuchFieldException e) {
                LogUtils.d(TAG, e.getMessage());
            } catch (IllegalAccessException e) {
                LogUtils.d(TAG, e.getMessage());
            } catch (IllegalArgumentException e) {
                LogUtils.d(TAG, e.getMessage());
            }
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        return false;
    }

    /**
     * return AM or PM
     *
     * @param tp
     * @return AM or PM
     */
    private AlarmData.AMPM getAmPm(TimePicker tp) {
        if (tp.getCurrentHour() < 12) {
            return AlarmData.AMPM.AM;
        } else {
            return AlarmData.AMPM.PM;
        }
    }

    /**
     * set title for actionbar
     */
    private void setActionBar() {
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //noinspection deprecation
            if (mIdAlarm != ConstantUtils.NEW_ALARM_ID) {
                actionBar.setTitle(ConstantUtils.SPACE_STRING + getResources().getString(R.string.edit_alarm_title));
            } else {
                actionBar.setTitle(ConstantUtils.SPACE_STRING + getResources().getString(R.string.add_alarm_title));
            }
            actionBar.setIcon(getResources().getDrawable(R.drawable.logo__melody));
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        if (textView.getId() == R.id.ed_label) {
            if (i == EditorInfo.IME_ACTION_NEXT) {
                hideKeyboard(mLabelEdt);
                return true;
            }
        }

        return false;
    }

    @Override
    public void onBackPressed() {
        closeAddAlarmActivity(mOldAlarm);
    }

    /**
     * check melody when click button Cancel and click button Back
     */
    private void closeAddAlarmActivity(AlarmData oldAlarm) {
        boolean[] daysTemp = mListDay.getDaysRepeat();
        AlarmData tempAlarm;
        tempAlarm = new AlarmData(mLabelEdt.getText().toString().trim(), mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute(), getAmPm(mTimePicker), daysTemp, mRepeatCb.isChecked(), mEnabled, mSoundData, mSoundTime);

        if (mAddAlarmActivityPresenter.cancelButtonClick(oldAlarm, tempAlarm)) {
            //show dialog
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                mNoSaveDialog.show(getFragmentManager(), null);
            }
        } else {
            finish();
        }
    }

    private void setupUI(View view) {
        // Set up touch listener for non-text box views to hide keyboard.
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    InputMethodManager inputMethodManager =
                            (InputMethodManager) getSystemService(
                                    Activity.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(), 0);
                    return false;
                }
            });
        }

        //If a layout container, iterate over children and seed recursion.
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setupUI(innerView);
            }
        }
    }

    /**
     * hiden keyboard
     *
     * @param editText
     */
    private void hideKeyboard(EditText editText) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(),
                InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
            switch (i) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    hideKeyboard(mLabelEdt);
                    return true;
                default:
                    break;
            }
        }
        return false;
    }

    private int getLastRepeatDay(AlarmData alarmData) {
        int lastRepeatDay = -1;
        int startDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - ConstantUtils.OFFSET_DAY_OF_WEEK;
        // Check day previous startDay.
        if (startDay > 0) {
            for (int i = startDay - 1; i >= 0; --i) {
                if (alarmData.getDays()[i]) {
                    lastRepeatDay = i;
                    break;
                }
            }
        }

        // Check day after startDay.
        if (lastRepeatDay == -1) {
            for (int i = alarmData.getDays().length - 1; i > 0; --i) {
                if (alarmData.getDays()[i]) {
                    lastRepeatDay = i;
                    break;
                }
            }
        }
        return lastRepeatDay;
    }

    private void clickButtonSave() {
        boolean[] daysTemp;
        daysTemp = mListDay.getDaysRepeat();

        if (!mListDay.selectedDay()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                mNoSelectDay.show(getFragmentManager(), null);
            }
        } else {
            String tempString = mLabelEdt.getText().toString().trim();
            tempString = tempString.replaceAll(ConstantUtils.WHITE_SPACE_REGEX, ConstantUtils.SPACE_STRING);

            final AlarmData saveAlarm = new AlarmData(tempString, mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute(), getAmPm(mTimePicker), daysTemp, mRepeatCb.isChecked(), true, mSoundData, mSoundTime);
            saveAlarm.setId(mIdAlarm);
            boolean checkAlarm = mAddAlarmActivityPresenter.validateAlarm(saveAlarm);
            if (checkAlarm) {
                saveAlarm.setLastRepeatDay(getLastRepeatDay(saveAlarm));
                final ProgressDialogFragment progressDialog = ProgressDialogFragment.newInstance(getString(R.string.progress_dialog_msg_save));
                if (mIdAlarm == ConstantUtils.NEW_ALARM_ID) {//add
                    progressDialog.show(getFragmentManager(), null);
                    mAddAlarmActivityPresenter.addAlarm(saveAlarm, new DBManager.OnSaveDataResultListener() {
                        @Override
                        public void onSuccess() {
                            progressDialog.dismissAllowingStateLoss();
                            sendBroadcastAddAlarm(saveAlarm);
                            finish();
                        }

                        @Override
                        public void onError(int i) {
                            progressDialog.dismissAllowingStateLoss();
                            CommonUtils.showHDDErrorDialog(AddAlarmActivity.this, i);
                        }
                    });

                } else {
                    if (!mAddAlarmActivityPresenter.cancelButtonClick(mOldAlarm, saveAlarm)) {
                        // nothing changed
                        finish();
                        return;
                    }

                    //edit
                    saveAlarm.setEnabled(true);
                    progressDialog.show(getFragmentManager(), null);
                    mAddAlarmActivityPresenter.editAlarm(saveAlarm, new DBManager.OnSaveDataResultListener() {
                        @Override
                        public void onSuccess() {
                            progressDialog.dismissAllowingStateLoss();
                            cancelOldAlarm();
                            sendBroadcastAddAlarm(saveAlarm);
                            finish();
                        }

                        @Override
                        public void onError(int i) {
                            progressDialog.dismissAllowingStateLoss();
                            CommonUtils.showHDDErrorDialog(AddAlarmActivity.this, i);
                        }
                    });
                }
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    mOverrideTime.show(getFragmentManager(), null);
                }
            }
        }
    }

    private void clickImageViewSound() {
        msoundListDialogFragment = SoundListDialogFragment.newInstance(mSoundData);
        msoundListDialogFragment.setOnDismissListener(new SoundListDialogFragment.OnSoundDialogDismissListener() {
            @Override
            public void onDismiss(SoundData soundData) {
                if (soundData != null) {
                    mSoundData = soundData;
                    mSoundTitleTv.setText(soundData.getTitle());
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            msoundListDialogFragment.show(getFragmentManager(), null);
        }
    }

    private void clickSoundTime() {
       SoundTimeListDialogFragment soundTimeListDialogFragment = SoundTimeListDialogFragment.newInstance(mSoundTime);
        soundTimeListDialogFragment.setOnSoundTimeDialogDismissListener(new SoundTimeListDialogFragment.OnSoundTimeDialogDismissListener() {
            @Override
            public void onDismiss(String soundTime) {
                mSoundTime = soundTime;
                mSoundTimeTv.setText(soundTime);
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            soundTimeListDialogFragment.show(getFragmentManager(), null);
        }

    }

    private void cancelOldAlarm() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE);
        Intent intentAlarm = new Intent(getApplicationContext(),
                AlarmService.class);
        PendingIntent morningIntent = PendingIntent.getBroadcast(getApplicationContext(), mIdAlarm,
                intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.cancel(morningIntent);
        morningIntent.cancel();
    }

    private class MyReceiver extends BroadcastReceiver {

        private final String SYSTEM_DIALOG_REASON_KEY = "reason";
        private final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason == null)
                    return;

                // Home
                if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                    AddAlarmActivity.this.finish();
                }


            }else if(SYS_NOTIFY_AUTH_STATE_CHANGED.equals(action)) {
                boolean login = intent.getBooleanExtra(LOGIN_STATUS, false);

                    // finish when user logout and login
                    AddAlarmActivity.this.finish();

            } else if (ACTION_POWER_MODE_CHANGED.equals(action)) {
                int mode = intent.getIntExtra(POWER_MODE, -1);
                // finish when enter sleeping mode
                if (Const.SLEEPING_MODE == mode) {
                    AddAlarmActivity.this.finish();
                }
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                // finish when screen off
                msoundListDialogFragment.dismissAllowingStateLoss();
                AddAlarmActivity.this.finish();


            } else if(Intent.ACTION_SCREEN_ON.equals(action)){
                AddAlarmActivity.this.finish();
            }
            else {
                // do nothing
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

}
